<?php
namespace Home\Model;

use  Think\Model;

class WechatModel extends Model
{
  protected $autoCheckFields = false;
  //检查是否在微信环境下
  public function check_is_weixin()
  {
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
      return true;
    }
    return false;
  }

  //微信公众号获取openid
  public function get_openid($code)
  {
    $wxJsonUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?";
    $wxJsonUrl .= 'appid='.C('cappid');
    $wxJsonUrl .= '&secret='.C('cappsecret');
    $wxJsonUrl .= '&code='.$code;
    $wxJsonUrl .= '&grant_type=authorization_code';
    $res = json_decode($this->httpGet($wxJsonUrl), true);

    return $res['openid'];
  }

  public function get_code($p)
  {
    if (!empty($p["state"]) && !empty($p["redirect_uri"])) {
      $wxUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?';

      $wxUrl .= 'appid='.C('cappid');
      $wxUrl .= '&redirect_uri='.urlencode($p['redirect_uri']);
      $wxUrl .= '&response_type=code&scope=snsapi_base';
      $wxUrl .= '&state='.$p["state"];
      $wxUrl .= '#wechat_redirect';
      return $wxUrl;
    }
  }

  //小程序获取openid
  public function get_openid_applet($js_code, $app_id)
  {
    $app_info = D('apps')->get_app_info($app_id);
    $wxJsonUrl = "https://api.weixin.qq.com/sns/jscode2session?";
    $wxJsonUrl .= 'appid='.$app_info['cappid_applet'];
    $wxJsonUrl .= '&secret='.$app_info['cappsecret_applet'];
    $wxJsonUrl .= '&js_code='.$js_code;
    $wxJsonUrl .= '&grant_type=authorization_code';
    $res = json_decode($this->httpGet($wxJsonUrl), true);

    return $res;
  }

  public function get_code_applet($p)
  {
    if (!empty($p["state"]) && !empty($p["redirect_uri"])) {
      $wxUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?';

      $wxUrl .= 'appid='.C('cappid');
      $wxUrl .= '&redirect_uri='.urlencode($p['redirect_uri']);
      $wxUrl .= '&response_type=code&scope=snsapi_base';
      $wxUrl .= '&state='.$p["state"];
      $wxUrl .= '#wechat_redirect';
      return $wxUrl;
    }
  }

  private function createNonceStr($length = 16)
  {
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $str = "";
    for ($i = 0; $i < $length; $i++) {
      $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
  }

  public function httpGet($url)
  {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_URL, $url);

    $res = curl_exec($curl);
    curl_close($curl);

    return $res;
  }
  
  public function postSend($url, $param)
  {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
  }
}
